import * as Cesium from 'cesium';

export class AppearanceManager {
  constructor(cesiumManager) {
    this.cesiumManager = cesiumManager;
    this.customMaterials = new Map();
    this.cityModels = new Map();
    this.particleSystems = new Map();
    // 添加帧率显示相关属性
    this.frameRateDisplay = null;
    this.frameRateElement = null;
    this.frameRateUpdateInterval = null;
    // 添加第三方插件管理
    this.thirdPartyPlugins = new Map();
  }

  /**
   * 创建自定义材质
   * @param {String} name - 材质名称
   * @param {Object} options - 材质选项
   * @returns {Material} 创建的材质
   */
  createCustomMaterial(name, options) {
    if (!name || !options) {
      throw new Error('Material name and options are required');
    }

    let material;
    switch (options.type) {
      case 'color':
        material = new Cesium.Material({
          fabric: {
            type: 'Color',
            uniforms: {
              color: options.color || new Cesium.Color(1.0, 0.0, 0.0, 1.0)
            }
          }
        });
        break;
        
      case 'image':
        material = new Cesium.Material({
          fabric: {
            type: 'Image',
            uniforms: {
              image: options.image,
              repeat: options.repeat || new Cesium.Cartesian2(1, 1)
            }
          }
        });
        break;
        
      case 'custom':
        material = new Cesium.Material({
          fabric: options.fabric
        });
        break;
        
      default:
        throw new Error('Unsupported material type');
    }

    this.customMaterials.set(name, material);
    return material;
  }

  /**
   * 获取自定义材质
   * @param {String} name - 材质名称
   * @returns {Material|undefined} 材质对象
   */
  getCustomMaterial(name) {
    return this.customMaterials.get(name);
  }

  /**
   * 删除自定义材质
   * @param {String} name - 材质名称
   */
  removeCustomMaterial(name) {
    this.customMaterials.delete(name);
  }

  /**
   * 渲染城市白膜模型
   * @param {Array} buildings - 建筑物数据数组
   * @param {Object} options - 渲染选项
   * @returns {Array} 添加的实体数组
   */
  renderCityWhiteModel(buildings, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const viewer = this.cesiumManager.viewer;
    const entities = [];
    
    // 默认选项
    const defaultOptions = {
      baseHeight: 0,
      wallMaterial: new Cesium.Color(0.9, 0.9, 0.9, 1.0),
      topMaterial: new Cesium.Color(1.0, 1.0, 1.0, 1.0),
      outline: true,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 1.0,
      extrudedHeight: 100
    };
    
    const renderOptions = Object.assign({}, defaultOptions, options);
    
    buildings.forEach((building, index) => {
      const id = building.id || `building_${index}`;
      
      // 创建建筑墙体
      const wallEntity = viewer.entities.add({
        id: `${id}_wall`,
        name: `${id}_wall`,
        wall: {
          positions: Cesium.Cartesian3.fromDegreesArrayHeights(
            building.positions.flatMap(pos => [pos.longitude, pos.latitude, pos.height || renderOptions.baseHeight])
          ),
          maximumHeights: building.positions.map(pos => pos.height || renderOptions.extrudedHeight),
          minimumHeights: building.positions.map(() => renderOptions.baseHeight),
          material: renderOptions.wallMaterial,
          outline: renderOptions.outline,
          outlineColor: renderOptions.outlineColor,
          outlineWidth: renderOptions.outlineWidth
        }
      });
      
      // 创建建筑顶部
      const topEntity = viewer.entities.add({
        id: `${id}_top`,
        name: `${id}_top`,
        polygon: {
          hierarchy: Cesium.Cartesian3.fromDegreesArray(
            building.positions.flatMap(pos => [pos.longitude, pos.latitude])
          ),
          height: building.positions[0].height || renderOptions.extrudedHeight,
          material: renderOptions.topMaterial,
          outline: renderOptions.outline,
          outlineColor: renderOptions.outlineColor,
          outlineWidth: renderOptions.outlineWidth
        }
      });
      
      entities.push(wallEntity, topEntity);
      this.cityModels.set(id, { wall: wallEntity, top: topEntity });
    });
    
    return entities;
  }

  /**
   * 更新建筑物样式
   * @param {String} buildingId - 建筑物ID
   * @param {Object} styleOptions - 样式选项
   */
  updateBuildingStyle(buildingId, styleOptions) {
    const building = this.cityModels.get(buildingId);
    if (!building) return;

    if (styleOptions.wallMaterial && building.wall) {
      building.wall.wall.material = styleOptions.wallMaterial;
    }
    
    if (styleOptions.topMaterial && building.top) {
      building.top.polygon.material = styleOptions.topMaterial;
    }
    
    if (styleOptions.extrudedHeight) {
      if (building.wall) {
        building.wall.wall.maximumHeights = building.wall.wall.positions.getValue().map(() => styleOptions.extrudedHeight);
      }
      if (building.top) {
        building.top.polygon.height = styleOptions.extrudedHeight;
      }
    }
  }

  /**
   * 高亮建筑物
   * @param {String} buildingId - 建筑物ID
   * @param {Object} highlightOptions - 高亮选项
   */
  highlightBuilding(buildingId, highlightOptions = {}) {
    const building = this.cityModels.get(buildingId);
    if (!building) return;
    
    const defaultHighlight = {
      wallMaterial: Cesium.Color.YELLOW,
      topMaterial: Cesium.Color.YELLOW.withAlpha(0.8),
      outlineColor: Cesium.Color.RED,
      outlineWidth: 2.0
    };
    
    const options = Object.assign({}, defaultHighlight, highlightOptions);
    
    if (building.wall) {
      building.wall.wall.material = options.wallMaterial;
      building.wall.wall.outlineColor = options.outlineColor;
      building.wall.wall.outlineWidth = options.outlineWidth;
    }
    
    if (building.top) {
      building.top.polygon.material = options.topMaterial;
      building.top.polygon.outlineColor = options.outlineColor;
      building.top.polygon.outlineWidth = options.outlineWidth;
    }
  }

  /**
   * 取消高亮建筑物
   * @param {String} buildingId - 建筑物ID
   */
  unhighlightBuilding(buildingId) {
    const building = this.cityModels.get(buildingId);
    if (!building) return;
    
    // 恢复默认样式（这里可以根据需要调整）
    if (building.wall) {
      building.wall.wall.material = new Cesium.Color(0.9, 0.9, 0.9, 1.0);
      building.wall.wall.outlineColor = Cesium.Color.BLACK;
      building.wall.wall.outlineWidth = 1.0;
    }
    
    if (building.top) {
      building.top.polygon.material = new Cesium.Color(1.0, 1.0, 1.0, 1.0);
      building.top.polygon.outlineColor = Cesium.Color.BLACK;
      building.top.polygon.outlineWidth = 1.0;
    }
  }

  /**
   * 创建粒子特效系统
   * @param {String} id - 粒子系统ID
   * @param {Object} options - 粒子系统选项
   * @returns {ParticleSystem} 创建的粒子系统
   */
  createParticleSystem(id, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const viewer = this.cesiumManager.viewer;
    
    // 默认配置
    const defaultOptions = {
      image: this._getDefaultParticleImage(),
      emissionRate: 50,
      lifetime: 5.0,
      startScale: 1.0,
      endScale: 0.0,
      color: Cesium.Color.WHITE,
      particleSize: 5.0,
      emitter: new Cesium.SphereEmitter(1.0),
      
    };

    // 合并配置
    const particleOptions = Object.assign({}, defaultOptions, options);

    // 创建粒子系统
    const particleSystem = viewer.scene.primitives.add(new Cesium.ParticleSystem({
      image: particleOptions.image,
      emissionRate: particleOptions.emissionRate,
      emitter: particleOptions.emitter,
      bursts: particleOptions.bursts,
      lifetime: particleOptions.lifetime,
      startColor: particleOptions.color,
      endColor: particleOptions.color.withAlpha(0.0),
      startScale: particleOptions.startScale,
      endScale: particleOptions.endScale,
      sizeInMeters: particleOptions.particleSize,
      updateCallback: particleOptions.updateCallback
    }));

    this.particleSystems.set(id, particleSystem);
    return particleSystem;
  }

  /**
   * 获取粒子系统
   * @param {String} id - 粒子系统ID
   * @returns {ParticleSystem|undefined} 粒子系统对象
   */
  getParticleSystem(id) {
    return this.particleSystems.get(id);
  }

  /**
   * 更新粒子系统配置
   * @param {String} id - 粒子系统ID
   * @param {Object} options - 更新选项
   */
  updateParticleSystem(id, options) {
    const particleSystem = this.particleSystems.get(id);
    if (!particleSystem) return;
    
    // 更新粒子系统属性
    if (options.emissionRate !== undefined) {
      particleSystem.emissionRate = options.emissionRate;
    }
    
    if (options.lifetime !== undefined) {
      particleSystem.lifetime = options.lifetime;
    }
    
    if (options.color !== undefined) {
      particleSystem.startColor = options.color;
      particleSystem.endColor = options.color.withAlpha(0.0);
    }
    
    if (options.particleSize !== undefined) {
      particleSystem.sizeInMeters = options.particleSize;
    }
  }

  /**
   * 删除粒子系统
   * @param {String} id - 粒子系统ID
   */
  removeParticleSystem(id) {
    const particleSystem = this.particleSystems.get(id);
    if (particleSystem) {
      if (this.cesiumManager && this.cesiumManager.viewer) {
        this.cesiumManager.viewer.scene.primitives.remove(particleSystem);
      }
      this.particleSystems.delete(id);
    }
  }

  /**
   * 创建烟花效果
   * @param {String} id - 效果ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {Object} options - 选项
   * @returns {Array} 粒子系统数组
   */
  createFireworkEffect(id, position, options = {}) {
    const cartesianPosition = Cesium.Cartesian3.fromDegrees(
      position.longitude, 
      position.latitude, 
      position.height || 100  // 修改: 降低默认高度，使烟花更接近地面
    );

    // 创建爆炸效果
    const explosionSystem = this.createParticleSystem(`${id}_explosion`, {
      image: this._getDefaultParticleImage(),
      emissionRate: 0, // 瞬间发射
      bursts: [
        new Cesium.ParticleBurst({
          time: 0.0,
          minimum: options.particleCount || 100,
          maximum: options.particleCount || 200
        })
      ],
      lifetime: options.lifetime || 2.0,
      startScale: options.startScale || 1.0,
      endScale: options.endScale || 0.0,
      color: options.color || Cesium.Color.fromRandom({alpha: 1.0}),
      particleSize: options.particleSize || 15.0,
      emitter: new Cesium.SphereEmitter(options.emitterRadius || 0.1),
      updateCallback: (particle) => {
        // 添加重力效果
        particle.velocity.z -= (options.gravity || 9.8) * particle.mass * 0.01;
      }
    });
    
    // 设置粒子系统的初始位置
    explosionSystem.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(cartesianPosition);
    
    return [explosionSystem];
  }

  /**
   * 触发烟花效果
   * @param {String} id - 效果ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {Number} count - 烟花数量
   * @param {Object} options - 选项
   */
  triggerFireworkEffect(id, position, count = 1, options = {}) {
    const effects = [];
    for (let i = 0; i < count; i++) {
      // 为每个烟花添加一些随机偏移
      const offsetPosition = {
        longitude: position.longitude + (Math.random() - 0.5) * 0.01,
        latitude: position.latitude + (Math.random() - 0.5) * 0.01,
        height: position.height || 100 // 修改: 修正高度值，与createFireworkEffect保持一致
      };
      
      const effectId = `${id}_${i}`;
      const effect = this.createFireworkEffect(effectId, offsetPosition, options);
      effects.push(...effect);
    }
    // 添加: 立即触发所有粒子系统的爆发
    effects.forEach(system => {
      if (system.bursts && system.bursts.length > 0) {
        system.bursts.forEach(burst => {
          console.log(burst,'burst')
          // system.emit(burst);
        });
      }
    });
    return effects;
  }

  /**
   * 创建雨雪效果
   * @param {String} id - 效果ID
   * @param {String} type - 类型 'rain' 或 'snow'
   * @param {Object} options - 选项
   * @returns {ParticleSystem} 粒子系统
   */
  createWeatherEffect(id, type = 'rain', options = {}) {
    // 默认配置
    const defaultWeatherOptions = {
      particleCount: 1000,
      speed: type === 'rain' ? 50 : 10,
      size: type === 'rain' ? 2 : 5,
      color: type === 'rain' ? Cesium.Color.BLUE : Cesium.Color.WHITE
    };
    
    const weatherOptions = Object.assign({}, defaultWeatherOptions, options);
    
    // 创建盒子发射器，覆盖整个视图区域
    const emitterRegion = new Cesium.BoxEmitter(new Cesium.Cartesian3(1000000.0, 1000000.0, 100000.0));
    
    // 创建天气粒子系统
    const weatherSystem = this.createParticleSystem(id, {
      emissionRate: weatherOptions.particleCount / 10,
      startVelocity: new Cesium.Cartesian3(0, 0, -weatherOptions.speed),
      lifetime: 10.0,
      startScale: 1.0,
      endScale: 1.0,
      color: weatherOptions.color,
      particleSize: weatherOptions.size,
      emitter: emitterRegion,
      updateCallback: (particle) => {
        // 循环粒子位置
        if (particle.position.z < -100000.0) {
          particle.position = new Cesium.Cartesian3(
            particle.position.x,
            particle.position.y,
            100000.0
          );
        }
      }
    });
    
    return weatherSystem;
  }

  /**
   * 创建烟雾效果
   * @param {String} id - 效果ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {Object} options - 选项
   * @returns {ParticleSystem} 粒子系统
   */
  createSmokeEffect(id, position, options = {}) {
    const cartesianPosition = Cesium.Cartesian3.fromDegrees(
      position.longitude, 
      position.latitude, 
      position.height || 10  // 修改: 降低烟雾默认高度
    );

    // 默认配置
    const defaultSmokeOptions = {
      color: Cesium.Color.GRAY.withAlpha(0.5),
      particleSize: 30,
      emissionRate: 20,
      lifetime: 10.0
    };
    
    const smokeOptions = Object.assign({}, defaultSmokeOptions, options);
    
    // 创建烟雾粒子系统
    const smokeSystem = this.createParticleSystem(id, {
      image: this._getDefaultParticleImage(),
      startVelocity: new Cesium.Cartesian3(2, 0, 5),
      emissionRate: smokeOptions.emissionRate,
      lifetime: smokeOptions.lifetime,
      startScale: 1.0,
      endScale: 5.0,
      color: smokeOptions.color,
      particleSize: smokeOptions.particleSize,
      emitter: new Cesium.ConeEmitter(Cesium.Math.toRadians(30)),
      updateCallback: (particle) => {
        // 添加风力和扩散效果
        particle.velocity.x += 0.1;
        particle.velocity.z += 0.05;
      }
    });
    
    // 设置烟雾系统的初始位置
    smokeSystem.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(cartesianPosition);
    
    return smokeSystem;
  }

  /**
   * 创建下雨效果，以长沙市为中心
   * @param {String} id - 效果ID
   * @param {Object} options - 选项
   * @returns {ParticleSystem} 粒子系统
   */
  createRainEffect(id, options = {}) {
    // 长沙市经纬度
    const changshaPosition = Cesium.Cartesian3.fromDegrees(112.938814, 28.196215, 3000);
    
    // 默认配置
    const defaultRainOptions = {
      particleCount: 2000,
      speed: 30,
      size: 1,
      color: Cesium.Color.BLUE.withAlpha(0.7),
      spread: 50000 // 雨滴分布范围
    };
    
    const rainOptions = Object.assign({}, defaultRainOptions, options);
    
    // 创建盒子发射器，以长沙市为中心
    const emitterRegion = new Cesium.BoxEmitter(new Cesium.Cartesian3(
      rainOptions.spread, 
      rainOptions.spread, 
      30000.0
    ));
    
    // 创建下雨粒子系统
    const rainSystem = this.createParticleSystem(id, {
      emissionRate: rainOptions.particleCount / 10,
      startVelocity: new Cesium.Cartesian3(2, 1, -rainOptions.speed), // 添加一些水平风力
      lifetime: 15.0,
      startScale: 1.0,
      endScale: 1.0,
      color: rainOptions.color,
      particleSize: rainOptions.size,
      emitter: emitterRegion,
      updateCallback: (particle) => {
        // 添加重力效果
        particle.velocity.z -= 9.8 * 0.1;
        
        // 循环粒子位置
        if (particle.position.z < -10000.0) {
          particle.position = new Cesium.Cartesian3(
            particle.position.x,
            particle.position.y,
            30000.0
          );
        }
      }
    });
    
    // 设置粒子系统的初始位置为长沙市上空
    rainSystem.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(changshaPosition);
    
    return rainSystem;
  }

  /**
   * 创建火焰效果
   * @param {String} id - 效果ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {Object} options - 选项
   * @returns {ParticleSystem} 粒子系统
   */
  createFireEffect(id, position, options = {}) {
    const cartesianPosition = Cesium.Cartesian3.fromDegrees(
      position.longitude,
      position.latitude,
      position.height || 0
    );

    // 默认配置
    const defaultFireOptions = {
      particleSize: 30,
      emissionRate: 50,
      lifetime: 1.0,
      color: Cesium.Color.ORANGE
    };

    const fireOptions = Object.assign({}, defaultFireOptions, options);

    // 创建火焰粒子系统
    const fireSystem = this.createParticleSystem(id, {
      image: this._getDefaultParticleImage(),
      emissionRate: fireOptions.emissionRate,
      lifetime: fireOptions.lifetime,
      startScale: 1.0,
      endScale: 0.1,
      color: fireOptions.color,
      particleSize: fireOptions.particleSize,
      emitter: new Cesium.ConeEmitter(Cesium.Math.toRadians(30)),
      updateCallback: (particle) => {
        // 火焰向上运动并逐渐变小
        particle.velocity.z += 5.0;
        particle.position.x += (Math.random() - 0.5) * 0.5;
        particle.position.y += (Math.random() - 0.5) * 0.5;
      }
    });

    // 设置火焰系统的初始位置
    fireSystem.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(cartesianPosition);

    return fireSystem;
  }

  /**
   * 创建爆炸效果
   * @param {String} id - 效果ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {Object} options - 选项
   * @returns {ParticleSystem} 粒子系统
   */
  createExplosionEffect(id, position, options = {}) {
    const cartesianPosition = Cesium.Cartesian3.fromDegrees(
      position.longitude,
      position.latitude,
      position.height || 10
    );

    // 默认配置
    const defaultExplosionOptions = {
      particleCount: 200,
      particleSize: 20,
      lifetime: 2.0,
      color: Cesium.Color.RED
    };

    const explosionOptions = Object.assign({}, defaultExplosionOptions, options);

    // 创建爆炸粒子系统
    const explosionSystem = this.createParticleSystem(id, {
      image: this._getDefaultParticleImage(),
      emissionRate: 0, // 瞬间发射所有粒子
      bursts: [
        new Cesium.ParticleBurst({
          time: 0.0,
          minimum: explosionOptions.particleCount,
          maximum: explosionOptions.particleCount
        })
      ],
      lifetime: explosionOptions.lifetime,
      startScale: 1.0,
      endScale: 0.0,
      color: explosionOptions.color,
      particleSize: explosionOptions.particleSize,
      emitter: new Cesium.SphereEmitter(5.0),
      updateCallback: (particle) => {
        // 添加重力和扩散效果
        particle.velocity.z -= 9.8 * 0.05;
        particle.position.x += (Math.random() - 0.5) * 2;
        particle.position.y += (Math.random() - 0.5) * 2;
      }
    });

    // 设置爆炸系统的初始位置
    explosionSystem.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(cartesianPosition);

    return explosionSystem;
  }

  /**
   * 创建喷泉效果
   * @param {String} id - 效果ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {Object} options - 选项
   * @returns {ParticleSystem} 粒子系统
   */
  createFountainEffect(id, position, options = {}) {
    const cartesianPosition = Cesium.Cartesian3.fromDegrees(
      position.longitude,
      position.latitude,
      position.height || 0
    );

    // 默认配置
    const defaultFountainOptions = {
      particleSize: 8,
      emissionRate: 100,
      lifetime: 3.0,
      color: Cesium.Color.BLUE
    };

    const fountainOptions = Object.assign({}, defaultFountainOptions, options);

    // 创建喷泉粒子系统
    const fountainSystem = this.createParticleSystem(id, {
      image: this._getDefaultParticleImage(),
      emissionRate: fountainOptions.emissionRate,
      lifetime: fountainOptions.lifetime,
      startScale: 1.0,
      endScale: 0.0,
      color: fountainOptions.color,
      particleSize: fountainOptions.particleSize,
      emitter: new Cesium.CircleEmitter(0.1),
      updateCallback: (particle) => {
        // 粒子向上喷射并受重力影响
        particle.velocity.z += 20.0;
        particle.velocity.z -= 9.8 * 0.1;
      }
    });

    // 设置喷泉系统的初始位置
    fountainSystem.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(cartesianPosition);

    return fountainSystem;
  }

  /**
   * 创建组合粒子效果（例如：烟雾+火焰）
   * @param {String} id - 效果ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {Array} effects - 效果配置数组
   * @returns {Array} 粒子系统数组
   */
  createCombinedEffect(id, position, effects) {
    const particleSystems = [];
    
    effects.forEach((effect, index) => {
      let system;
      switch (effect.type) {
        case 'fire':
          system = this.createFireEffect(`${id}_fire_${index}`, position, effect.options);
          break;
        case 'smoke':
          system = this.createSmokeEffect(`${id}_smoke_${index}`, position, effect.options);
          break;
        case 'explosion':
          system = this.createExplosionEffect(`${id}_explosion_${index}`, position, effect.options);
          break;
        default:
          console.warn(`Unsupported effect type: ${effect.type}`);
          return;
      }
      particleSystems.push(system);
    });
    
    return particleSystems;
  }

  /**
   * 启动粒子系统
   * @param {String} id - 粒子系统ID
   */
  startParticleSystem(id) {
    const particleSystem = this.particleSystems.get(id);
    if (particleSystem) {
      particleSystem.show = true;
    }
  }

  /**
   * 停止粒子系统
   * @param {String} id - 粒子系统ID
   */
  stopParticleSystem(id) {
    const particleSystem = this.particleSystems.get(id);
    if (particleSystem) {
      particleSystem.show = false;
    }
  }

  /**
   * 暂停粒子系统
   * @param {String} id - 粒子系统ID
   */
  pauseParticleSystem(id) {
    const particleSystem = this.particleSystems.get(id);
    if (particleSystem) {
      particleSystem.updateCallback = () => {}; // 清空更新回调以暂停动画
    }
  }

  /**
   * 恢复粒子系统
   * @param {String} id - 粒子系统ID
   * @param {Function} updateCallback - 更新回调函数
   */
  resumeParticleSystem(id, updateCallback) {
    const particleSystem = this.particleSystems.get(id);
    if (particleSystem && updateCallback) {
      particleSystem.updateCallback = updateCallback;
    }
  }

  /**
   * 获取默认粒子图像
   * @private
   * @returns {String} 图像URL
   */
  _getDefaultParticleImage() {
    // 创建一个简单的圆形粒子图像
    const canvas = document.createElement('canvas');
    canvas.width = 32;
    canvas.height = 32;
    const context = canvas.getContext('2d');
    
    context.beginPath();
    context.arc(16, 16, 16, 0, Cesium.Math.TWO_PI, true);
    context.closePath();
    context.fillStyle = 'rgba(202, 21, 21, 1)';
    context.fill();
    
    return canvas.toDataURL();
  }

  /**
   * 显示帧率
   * @param {Object} options - 显示选项
   */
  showFrameRate(options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      position: 'top-right', // top-left, top-right, bottom-left, bottom-right
      style: {
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        color: 'white',
        padding: '5px',
        fontFamily: 'Arial, sans-serif',
        fontSize: '12px',
        borderRadius: '3px'
      }
    };

    const showOptions = Object.assign({}, defaultOptions, options);

    // 创建显示帧率的DOM元素
    if (!this.frameRateElement) {
      this.frameRateElement = document.createElement('div');
      document.body.appendChild(this.frameRateElement);
    }

    // 应用样式
    Object.assign(this.frameRateElement.style, {
      position: 'fixed',
      zIndex: 9999,
      ...showOptions.style
    });

    // 设置位置
    switch (showOptions.position) {
      case 'top-left':
        this.frameRateElement.style.top = '10px';
        this.frameRateElement.style.left = '10px';
        break;
      case 'top-right':
        this.frameRateElement.style.top = '10px';
        this.frameRateElement.style.right = '10px';
        break;
      case 'bottom-left':
        this.frameRateElement.style.bottom = '10px';
        this.frameRateElement.style.left = '10px';
        break;
      case 'bottom-right':
        this.frameRateElement.style.bottom = '10px';
        this.frameRateElement.style.right = '10px';
        break;
    }

    // 开始更新帧率显示
    if (this.frameRateUpdateInterval) {
      clearInterval(this.frameRateUpdateInterval);
    }

    let lastTime = performance.now();
    let frameCount = 0;

    this.frameRateUpdateInterval = setInterval(() => {
      const currentTime = performance.now();
      frameCount++;

      if (currentTime - lastTime >= 1000) {
        const fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
        this.frameRateElement.textContent = `FPS: ${fps}`;
        frameCount = 0;
        lastTime = currentTime;
      }
    }, 500);
  }

  /**
   * 隐藏帧率显示
   */
  hideFrameRate() {
    if (this.frameRateUpdateInterval) {
      clearInterval(this.frameRateUpdateInterval);
      this.frameRateUpdateInterval = null;
    }

    if (this.frameRateElement) {
      document.body.removeChild(this.frameRateElement);
      this.frameRateElement = null;
    }
  }

  /**
   * 加载第三方插件
   * @param {String} pluginName - 插件名称
   * @param {Function} loader - 插件加载函数
   */
  loadThirdPartyPlugin(pluginName, loader) {
    if (this.thirdPartyPlugins.has(pluginName)) {
      console.warn(`Plugin ${pluginName} is already loaded`);
      return Promise.resolve(this.thirdPartyPlugins.get(pluginName));
    }

    try {
      const plugin = loader();
      this.thirdPartyPlugins.set(pluginName, plugin);
      console.log(`Plugin ${pluginName} loaded successfully`);
      return Promise.resolve(plugin);
    } catch (error) {
      console.error(`Failed to load plugin ${pluginName}:`, error);
      return Promise.reject(error);
    }
  }

  /**
   * 获取已加载的第三方插件
   * @param {String} pluginName - 插件名称
   * @returns {Object|undefined} 插件对象
   */
  getThirdPartyPlugin(pluginName) {
    return this.thirdPartyPlugins.get(pluginName);
  }

  /**
   * 卸载第三方插件
   * @param {String} pluginName - 插件名称
   */
  unloadThirdPartyPlugin(pluginName) {
    if (this.thirdPartyPlugins.has(pluginName)) {
      this.thirdPartyPlugins.delete(pluginName);
      console.log(`Plugin ${pluginName} unloaded`);
    }
  }

  /**
   * 获取可用的第三方插件列表
   * @returns {Array} 插件名称数组
   */
  getAvailablePlugins() {
    return Array.from(this.thirdPartyPlugins.keys());
  }

  /**
   * 应用场景美化效果
   * @param {Object} options - 美化选项
   */
  applySceneEnhancements(options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const viewer = this.cesiumManager.viewer;
    const scene = viewer.scene;

    // 雾效设置
    if (options.fog !== undefined) {
      scene.fog.enabled = options.fog.enabled || false;
      if (options.fog.enabled) {
        scene.fog.density = options.fog.density || 0.0002;
        scene.fog.screenSpaceErrorFactor = options.fog.screenSpaceErrorFactor || 2.0;
      }
    }

    // 光照设置
    if (options.lighting !== undefined) {
      scene.globe.enableLighting = options.lighting.enabled || false;
    }

    // 大气效果
    if (options.atmosphere !== undefined) {
      scene.skyAtmosphere.show = options.atmosphere.show !== false;
      if (options.atmosphere.brightness) {
        scene.skyAtmosphere.brightness = options.atmosphere.brightness;
      }
    }

    // 阴影设置
    if (options.shadows !== undefined) {
      viewer.shadows = options.shadows.enabled || false;
    }

    // 抗锯齿
    if (options.antialiasing !== undefined) {
      if (options.antialiasing.fxaa) {
        scene.fxaa = options.antialiasing.fxaa;
      }
    }

    // 后处理效果
    if (options.postProcessStages) {
      // 这里可以添加各种后处理效果
      console.log('Post-processing effects would be applied here');
    }
  }

  /**
   * 清理所有资源
   */
  destroy() {
    // 清理自定义材质
    this.customMaterials.clear();
    
    // 清理城市模型
    this.cityModels.clear();
    
    // 清理粒子系统
    for (const [id, particleSystem] of this.particleSystems.entries()) {
      if (this.cesiumManager && this.cesiumManager.viewer) {
        this.cesiumManager.viewer.scene.primitives.remove(particleSystem);
      }
    }
    this.particleSystems.clear();
    
    // 清理帧率显示
    this.hideFrameRate();
    
    // 清理第三方插件
    this.thirdPartyPlugins.clear();
  }

  // 实现简单的粒子效果 下雨的感觉 以长沙市为中心
}